package mo.offer_version2;

import mo.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class L34 {

    private int sum = 0;

    public List<List<Integer>> pathSum(TreeNode root, int target) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(res, new ArrayList<>(), root, target);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> candidate, TreeNode node, int target) {
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null && sum + node.val == target) {
            candidate.add(node.val);
            res.add(new ArrayList<>(candidate));
            candidate.remove(candidate.size()-1);
            return;
        }
        candidate.add(node.val);
        sum += node.val;
        dfs(res, candidate, node.left,  target);
        dfs(res, candidate, node.right, target);
        sum -= node.val;
        candidate.remove(candidate.size()-1);
    }

    public static void main(String[] args) {
        L34 test = new L34();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(3);
        root.right = new TreeNode(4);
        root.left.left = new TreeNode(1);
        System.out.println(test.pathSum(root, 5));
    }

}
